/**
 * 出生点对象,处理游戏中所有出生点发生的逻辑
 */
package labox.innovation.gameserver.model;

import java.lang.reflect.Constructor;

import java.util.List;

import javolution.util.FastList;
import labox.innovation.config.Config;
import labox.innovation.gameserver.datatables.NpcTemplateTable;
import labox.innovation.gameserver.idfactory.IdFactory;
import labox.innovation.gameserver.model.actor.L2Npc;
import labox.innovation.gameserver.templates.chars.NpcTemplate;
import labox.innovation.gameserver.timer.Timer;
import labox.innovation.util.Rnd;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * NPC出生/重生处理类，此类管理了一类NPC实例的出生和重生.
 * 
 * <B><U> Concept</U> :</B><BR>
 * <BR>
 * L2NpcInstance can be spawned either in a random position into a location area (if Lox=0 and Locy=0), either at an exact position. The heading of the L2NpcInstance can be a random heading if not defined (value= -1) or an exact heading (ex : merchant...).<BR>
 * <BR>
 */
public class L2Spawn {

	protected static final Logger _log = LoggerFactory.getLogger(L2Spawn.class.getName());

	/**
	 * 此重生点的NPC模板
	 */
	private final NpcTemplate _template;

	/**
	 * 重生点的ID
	 */
	private int _id;

	/**
	 * 重生点所在的场景ID
	 */
	private int _location;

	/**
	 * 重生点管理的最大的NPC数量
	 */
	private int _maximumCount;

	/**
	 * 重生点当前管理的NPC数量
	 */
	private int _currentCount;

	/**
	 * 重生点可以分配的NPC的数量
	 */
	protected int _scheduledCount;

	/**
	 * 重生点的X坐标
	 */
	private int _locX;

	/**
	 * 重生点的Y坐标
	 */
	private int _locY;

	/**
	 * 重生延迟。删除一个NPC和重生一个NPC的间隔时间
	 */
	private int _respawnDelay;

	/** Minimum delay RaidBoss */
	private int _respawnMinDelay;

	/** Maximum delay RaidBoss */
	private int _respawnMaxDelay;

	/**
	 * 重生点所在的副本ID
	 */
	private int _instanceId;

	/**
	 * 重生点出生的对象的通用构造函数
	 */
	private Constructor<?> _constructor;

	/**
	 * 是否开启重生操作
	 */
	private boolean _doRespawn;

	private L2Npc _lastSpawn;

	/**
	 * NPC出生是否随机坐标
	 */
	private boolean _randomSpawn;

	/**
	 * 重生点监听器
	 */
	private static List<SpawnListener> _spawnListeners = new FastList<SpawnListener>();

	/**
	 * 首次刷怪时间计时器
	 */
	private Timer _firstTimer;

	/**
	 *开服后第一周期怪物刷新的持续时间
	 */
	private long first_duration;

	/**
	 *开服后第一周期怪物刷新的周期
	 */
	private long first_cycle;

	/**
	 * 怪物刷新的周期
	 */
	private long _cycle;

	/**
	 * 怪物刷新周期计时器
	 */
	private Timer _cycleTimer;

	/**
	 * 怪物刷新的持续时间
	 */
	private long _duration;

	/**
	 * 怪物刷新的持续计时器
	 */
	private Timer _durationTimer;

	/**
	 * 时间到了是否删除NPC
	 */
	private boolean _deSpawn;

	/**
	 * The task launching the function doSpawn()
	 * 
	 * @author Administrator
	 * 
	 */
	class SpawnTask implements Runnable {

		private L2Npc _oldNpc;

		public SpawnTask(L2Npc pOldNpc) {
			_oldNpc = pOldNpc;
		}

		public void run() {
			try {
				// doSpawn();
				respawnNpc(_oldNpc);
			} catch (Exception e) {
				_log.error("SpawnTask error", Config.SERVER_ID, e);
			}

			_scheduledCount--;
		}
	}

	/**
	 * Constructor of L2Spawn.<BR>
	 * <BR>
	 * 
	 * <B><U> Concept</U> :</B><BR>
	 * <BR>
	 * Each L2Spawn owns generic and static properties (ex : RewardExp, RewardSP, AggroRange...). All of those properties are stored in a different L2NpcTemplate for each type of L2Spawn. Each template is loaded once in the server cache memory (reduce memory use). When a new instance of L2Spawn is created, server just create a link between the instance and the template. This link is stored in <B>_template</B><BR>
	 * <BR>
	 * 
	 * Each L2NpcInstance is linked to a L2Spawn that manages its spawn and respawn (delay, location...). This link is stored in <B>_spawn</B> of the L2NpcInstance<BR>
	 * <BR>
	 * 
	 * <B><U> Actions</U> :</B><BR>
	 * <BR>
	 * <li>Set the _template of the L2Spawn</li> <li>Calculate the implementationName used to generate the generic constructor of L2NpcInstance managed by this L2Spawn</li> <li>Create the generic constructor of L2NpcInstance managed by this L2Spawn</li><BR>
	 * <BR>
	 * 
	 * @param mobTemplate
	 *            The L2NpcTemplate to link to this L2Spawn
	 * 
	 */
	public L2Spawn(NpcTemplate mobTemplate) throws SecurityException, ClassNotFoundException, NoSuchMethodException {
		// 设置出生的NPC模板
		_template = mobTemplate;

		if (_template == null)
			return;

		// The Name of the L2NpcInstance type managed by this L2Spawn
		String implementationName = _template.type; // implementing class name

		// Create the generic constructor of L2NpcInstance managed by this
		// L2Spawn
		Class<?>[] parameters = { long.class, NpcTemplate.class };
		_constructor = Class.forName("labox.innovation.gameserver.model.actor.instance." + implementationName + "Instance").getConstructor(parameters);
	}

	public static final L2Spawn fromXML(Element e, int sceneId, int uid) {
		int id = Integer.parseInt(e.getAttribute("npc_templateid"));
		NpcTemplate template1 = NpcTemplateTable.getInstance().getTemplate(id);
		L2Spawn spawn = null;
		try {
			spawn = new L2Spawn(template1);
		} catch (Exception ex) {
			_log.error("spawn error NpcTemplate id:" + id + " | Exception :", Config.SERVER_ID, ex);
		}

		spawn.setLocx(Integer.parseInt(e.getAttribute("x")));
		spawn.setLocy(Integer.parseInt(e.getAttribute("y")));
		spawn.setRandomSpawn(Boolean.parseBoolean(e.getAttribute("random")));
		spawn.setAmount(Integer.parseInt(e.getAttribute("count")));
		spawn.setRespawnDelay(Integer.parseInt(e.getAttribute("respawn_delay")));
		spawn.setLocation(sceneId);
		spawn.setId(uid);

		NodeList nl = e.getChildNodes();
		//		for(int i=0;i<nl.getLength();i++)
		//		{
		//			if (nl.item(i).getNodeType() == Node.TEXT_NODE)
		//			{
		//				(Text) nl.item(i); 
		//			}
		//		}

		if (Boolean.parseBoolean(getNodeValue(nl, 1))) {
			//设置开放的周期
			spawn.setCycle(Long.parseLong(getNodeValue(nl, 5)) * getUnit2Millis(Integer.parseInt(getNodeValue(nl, 7))));
			//设置刷新持续的时间     runUnit=0  分  run =3
			spawn.setDuration(Long.parseLong(getNodeValue(nl, 9)) * getUnit2Millis(Integer.parseInt(getNodeValue(nl, 11))));
			//设置首次开放的时间
			spawn.setFirstStartTime(Long.parseLong(getNodeValue(nl, 3)) - System.currentTimeMillis());
			//时间结束是否删除NPC
			spawn.setDeSpawn(Boolean.parseBoolean(getNodeValue(nl, 13)));
		} else
			spawn._doRespawn = true;

		return spawn;
	}

	public static final String getNodeValue(NodeList nl, int i) {
		Node ex = nl.item(i);
		NamedNodeMap nnm = ex.getAttributes();
		if (nnm != null) {
			return nnm.getNamedItem("value").getNodeValue();
		}
		return null;
	}

	/**
	 * Create the initial spawning and set _doRespawn to True.<BR>
	 * <BR>
	 * 
	 * @return The number of L2NpcInstance that were spawned
	 */
	public int init() {
		while (_currentCount < _maximumCount && _doRespawn == true) {
			doSpawn();
		}
		// _doRespawn = true;

		return _currentCount;
	}

	public void setFirstStartTime(long time) {
		if (_firstTimer != null) {
			_firstTimer.cancel();
		}
		if (_cycleTimer != null) {
			_cycleTimer.cancel();
		}
		if (_durationTimer != null) {
			_durationTimer.cancel();
		}

		long alreadyRun = 0;
		if (time < 0 && _cycle>0) {
			alreadyRun = -time % _cycle; //现在时间 - 怪物定时开放时间 %(取余数) 定时周期时间	
			first_duration = _duration - alreadyRun; //第一个周期持续时间  
			first_cycle = _cycle - alreadyRun; //第一个周期 离第二个周期的 周期时间
		}else{
			first_duration = _duration ; //第一个周期持续时间  
			first_cycle = _cycle ; //第一个周期 离第二个周期的 周期时间
		}

		//延迟time时间后刷新怪物
		_firstTimer = new Timer(time, false, new Runnable() {
			public void run() {
				startRespawn();
				init();

					_durationTimer = new Timer(first_duration, true, new Runnable() {
						public void run() {
							stopRespawn();
							if (_deSpawn)
								doDespawn();
							_durationTimer.cancel();
						}
					});
					_durationTimer.start();


				if (_cycle > 0) {//如果周期>0,设置周期开放的时间
					_cycleTimer = new Timer(first_cycle, true, new Runnable() {
						public void run() {
							startRespawn();
							init();
							_durationTimer.setDelay(_duration);
							_durationTimer.start();
							_cycleTimer.setDelay(_cycle);
						}
					});
					_cycleTimer.start();
				}

				_firstTimer = null;
			}
		});
		_firstTimer.start();

	}

	/**
	 * 重生点管理的最大的NPC数量.<BR>
	 * <BR>
	 */
	public int getAmount() {
		return _maximumCount;
	}

	/**
	 * 重生点的ID.<BR>
	 * <BR>
	 */
	public int getId() {
		return _id;
	}

	/**
	 * 重生点所在的场景ID.<BR>
	 * <BR>
	 */
	public int getLocation() {
		return _location;
	}

	/**
	 * 重生点的X坐标.<BR>
	 * <BR>
	 */
	public int getLocx() {
		return _locX;
	}

	/**
	 * 重生点的Y坐标.<BR>
	 * <BR>
	 */
	public int getLocy() {
		return _locY;
	}

	/**
	 * 重生点的NPC模板ID.<BR>
	 * 
	 */
	public int getNpcid() {
		return _template._id;
	}

	/**
	 * 重生延迟。删除一个NPC和重生一个NPC的间隔时间.<BR>
	 * <BR>
	 */
	public int getRespawnDelay() {
		return _respawnDelay;
	}

	/**
	 * Return Min RaidBoss Spawn delay.<BR>
	 * <BR>
	 */
	public int getRespawnMinDelay() {
		return _respawnMinDelay;
	}

	/**
	 * Return Max RaidBoss Spawn delay.<BR>
	 * <BR>
	 */
	public int getRespawnMaxDelay() {
		return _respawnMaxDelay;
	}

	/**
	 * 设置重生点管理的最大的NPC数量.<BR>
	 * <BR>
	 */
	public void setAmount(int amount) {
		_maximumCount = amount;
	}

	/**
	 * Set the Identifier of this L2Spwan (used as key in the SpawnTable).<BR>
	 * <BR>
	 */
	public void setId(int id) {
		_id = id;
	}

	/**
	 * Set the Identifier of the location area where L2NpcInstance can be spwaned.<BR>
	 * <BR>
	 */
	public void setLocation(int location) {
		_location = location;
	}

	/**
	 * Set Minimum Respawn Delay.<BR>
	 * <BR>
	 */
	public void setRespawnMinDelay(int date) {
		_respawnMinDelay = date;
	}

	/**
	 * Set Maximum Respawn Delay.<BR>
	 * <BR>
	 */
	public void setRespawnMaxDelay(int date) {
		_respawnMaxDelay = date;
	}

	/**
	 * Set the X position of the spwan point.<BR>
	 * <BR>
	 */
	public void setLocx(int locx) {
		_locX = locx;
	}

	/**
	 * Set the Y position of the spwan point.<BR>
	 * <BR>
	 */
	public void setLocy(int locy) {
		_locY = locy;
	}

	public void setRandomSpawn(boolean rand) {
		_randomSpawn = rand;
	}

	public boolean getRandomSpawn() {
		return _randomSpawn;
	}

	/**
	 * 降低当前管理的NPC数量，如果有必要调取SpawnTask启动一个重生延迟.<BR>
	 * <BR>
	 * 
	 * <B><U> Actions</U> :</B><BR>
	 * <BR>
	 * <li>Decrease the current number of L2NpcInstance of this L2Spawn</li> <li>
	 * Check if respawn is possible to prevent multiple respawning caused by lag</li> <li>Update the current number of SpawnTask in progress or stand by of this L2Spawn</li> <li>Create a new SpawnTask to launch after the respawn Delay</li><BR>
	 * <BR>
	 * 
	 * <FONT COLOR=#FF0000><B> <U>Caution</U> : A respawn is possible ONLY if _doRespawn=True and _scheduledCount + _currentCount < _maximumCount</B></FONT><BR>
	 * <BR>
	 * 
	 */
	public void decreaseCount(L2Npc oldNpc) {
		if (_currentCount <= 0)
			return;

		// 减少当前的数量
		_currentCount--;

		// 检查是否能够再次分配出生的NPC
		if (_doRespawn && _scheduledCount + _currentCount < _maximumCount) {
			_scheduledCount++;
			// Create a new SpawnTask to launch after the respawn Delay
			// ClientScheduler.getInstance().scheduleLow(new SpawnTask(npcId),
			// _respawnDelay);
			new Timer(_respawnDelay, false, new SpawnTask(oldNpc)).start();
		}
	}

	/**
	 * Set _doRespawn to False to stop respawn in thios L2Spawn.<BR>
	 * <BR>
	 */
	public void stopRespawn() {
		_doRespawn = false;
	}

	/**
	 * Set _doRespawn to True to start or restart respawn in this L2Spawn.<BR>
	 * <BR>
	 */
	public void startRespawn() {
		_doRespawn = true;
	}

	/**
	 * Create the L2NpcInstance, add it to the world and lauch its OnSpawn action.<BR>
	 * <BR>
	 * 
	 * <B><U> Concept</U> :</B><BR>
	 * <BR>
	 * L2NpcInstance can be spawned either in a random position into a location area (if Lox=0 and Locy=0), either at an exact position. The heading of the L2NpcInstance can be a random heading if not defined (value= -1) or an exact heading (ex : merchant...).<BR>
	 * <BR>
	 * 
	 * <B><U> Actions for an random spawn into location area</U> : <I>(if Locx=0 and Locy=0)</I></B><BR>
	 * <BR>
	 * <li>Get L2NpcInstance Init parameters and its generate an Identifier</li> <li>Call the constructor of the L2NpcInstance</li> <li>Calculate the random position in the location area (if Locx=0 and Locy=0) or get its exact position from the L2Spawn</li> <li>Set the position of the L2NpcInstance</li> <li>Set the HP and MP of the L2NpcInstance to the max</li> <li>Set the heading of the L2NpcInstance (random heading if not defined : value=-1)</li> <li>Link the L2NpcInstance to this L2Spawn</li> <li>Init other values of the L2NpcInstance (ex : from its L2CharTemplate for INT, STR, DEX...) and add it in the world</li> <li>Lauch the action OnSpawn fo the L2NpcInstance</li><BR>
	 * <BR>
	 * <li>Increase the current number of L2NpcInstance managed by this L2Spawn</li> <BR>
	 * <BR>
	 * 
	 */
	public L2Npc doSpawn() {
		L2Npc mob = null;
		try {
			// Check if the L2Spawn is not a L2Pet or L2Minion or L2Decoy spawn
			if (_template.type.equalsIgnoreCase("L2Pet") || _template.type.equalsIgnoreCase("L2Minion") || _template.type.equalsIgnoreCase("L2FlyMinion") || _template.type.equalsIgnoreCase("L2Decoy") || _template.type.equalsIgnoreCase("L2Trap") || _template.type.equalsIgnoreCase("L2EffectPoint")) {
				_currentCount++;

				return mob;
			}

			// Get L2NpcInstance Init parameters and its generate an Identifier
			Object[] parameters = { IdFactory.getInstance().getNextId(IdFactory.ID_NPC), _template };

			// Call the constructor of the L2NpcInstance
			// (can be a L2ArtefactInstance, L2FriendlyMobInstance,
			// L2GuardInstance, L2MonsterInstance, L2SiegeGuardInstance,
			// L2BoxInstance,
			// L2FeedableBeastInstance, L2TamedBeastInstance, L2FolkInstance or
			// L2TvTEventNpcInstance)
			Object tmp = _constructor.newInstance(parameters);
			// 设置副本ID
			((L2Object) tmp).setInstanceId(_instanceId);

			// Check if the Instance is a L2NpcInstance
			if (!(tmp instanceof L2Npc))
				return mob;
			mob = (L2Npc) tmp;
			mob.setTitle(_template.title);
			mob.setName(_template.name);

			// NPC加入到游戏世界中
			FuzeWorld.getInstance().enterWorld(mob);

			return intializeNpcInstance(mob);
		} catch (Exception e) {
			_log.error("NPC " + _template._id + " class not found", Config.SERVER_ID, e);
		}
		return mob;
	}

	public void doDespawn() {
		L2Npc mob = null;
		try {
			for (; _currentCount > 0; _currentCount--) {
				Scene s = FuzeWorld.getInstance().getScene(getLocation());
				mob = (L2Npc) s.getObjects(this);
				mob.deleteMe();
			}

		} catch (Exception e) {
			_log.error("despawn error:npc:" + mob, Config.SERVER_ID, e);
		}
	}

	/**
	 * 初始化这个NPC并把NPC加入到可见世界中
	 * 
	 * @param mob
	 * @return
	 */
	private L2Npc intializeNpcInstance(L2Npc mob) {
		int newlocx, newlocy;

		// The L2NpcInstance is spawned at the exact position (Lox, Locy)

		int range = Config.MAX_DRIFT_RANGE;
		newlocx = getLocx();
		newlocy = getLocy();
		if (_randomSpawn) {
			newlocx += Rnd.get(-range, range);
			newlocy += Rnd.get(-range, range);
		}

		Location loc = FuzeWorld.getInstance().getScene(getLocation()).getGeoData().moveCheck(getLocx(), getLocy(), newlocx, newlocy);
		newlocx = loc.getX();
		newlocy = loc.getY();

		for (L2Effect f : mob.getAllEffects()) {
			if (f != null)
				mob.removeEffect(f);
		}

		mob.setIsDead(false);
		// Reset decay info
		mob.setDecayed(false);
		// Set the HP and MP of the L2NpcInstance to the max
		mob.getStatus().setCurrentHp(mob.getMaxHp(),false);
		mob.getStatus().setCurrentMp(mob.getMaxMp(),false);

		mob.reInitCharStatusUpdate();

		// 设置NPC的出生点
		mob.setSpawn(this);

		// 把NPC出生在可见世界中
		mob.spawnMe(getLocation(), newlocx, newlocy);

		L2Spawn.notifyNpcSpawned(mob);

		_lastSpawn = mob;

		if (_log.isDebugEnabled())
			_log.debug("spawned Mob ID: " + _template._id + " ,at: " + mob.getX() + " x, " + mob.getY() + " y", Config.SERVER_ID);

		// 增加重生点当前管理的NPC的数量
		_currentCount++;
		return mob;
	}

	public static void addSpawnListener(SpawnListener listener) {
		_spawnListeners.add(listener);
	}

	public static void removeSpawnListener(SpawnListener listener) {
		_spawnListeners.remove(listener);
	}

	public static void notifyNpcSpawned(L2Npc npc) {
		for (SpawnListener listener : _spawnListeners) {
			listener.npcSpawned(npc);
		}
	}

	/**
	 * @param i
	 *            delay in seconds
	 */
	public void setRespawnDelay(int i) {
		if (i < 0)
			_log.warn("respawn delay is negative for spawnId:" + _id, Config.SERVER_ID, "重生延迟设置异常");

		if (i < 10)
			i = 10;

		_respawnDelay = i * 1000;
	}

	public L2Npc getLastSpawn() {
		return _lastSpawn;
	}

	/**
	 * 重新出生此NPC
	 * 
	 * @param oldNpc
	 */
	public void respawnNpc(L2Npc oldNpc) {
		// oldNpc.refreshID();
		intializeNpcInstance(oldNpc);
	}

	public NpcTemplate getTemplate() {
		return _template;
	}

	public int getInstanceId() {
		return _instanceId;
	}

	public void setInstanceId(int instanceId) {
		_instanceId = instanceId;
	}

	public long getCycle() {
		return _cycle;
	}

	public void setCycle(long cycle) {
		_cycle = cycle;
	}

	public long getDuration() {
		return _duration;
	}

	public void setDuration(long duration) {
		_duration = duration;
	}

	public void setDeSpawn(boolean deSpawn) {
		_deSpawn = deSpawn;
	}

	public boolean isDeSpawn() {
		return _deSpawn;
	}

	private static final int MINUTE = 0;

	private static final int HOUR = 1;

	private static final int DAY = 2;

	private static final int WEEK = 3;

	private static final int MONTH = 4;

	public static long getUnit2Millis(int unit) {
		switch (unit) {
		case MINUTE:
			return 60 * 1000L;
		case HOUR:
			return 3600 * 1000L;
		case DAY:
			return 24 * 3600 * 1000L;
		case WEEK:
			return 7 * 24 * 3600 * 1000L;
		case MONTH:
			return 30 * 7 * 24 * 3600 * 1000L;
		default:
			return -1;
		}
	}
}
